/**
 * @Description: qiankun 父子应用配置
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 28/09/24 PM3:23
 */

import { type MicroApp } from 'qiankun'
import type { TRouter } from '@root/types/router.ts'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { bus, cache } from 'sf-utils2'

import { useRouterPlus } from '@/router/use-router-plus.ts'
import useAppSore from '@store/use-app-store.ts'
import useUserStore from '@store/use-user-store.ts'
import useLayoutStore from '@store/use-layout-store.ts'
import useMenusStore from '@store/use-menu-store.ts'

import setting from '@/setting.ts'

export const shared = {
  /**
   * 子应用映射
   */
  microApps: {} as Record<string, MicroApp>,

  /**
   * 错误的页面缓存
   */
  embedHTMLErrorCache: {} as Record<string, boolean>,

  /**
   * 主应用路由
   */
  router: undefined as TRouter,

  /**
   * 主应用路由
   */
  route: undefined as RouteLocationNormalizedLoaded,

  /**
   * 事件总线
   */
  bus,

  /**
   * 变量缓存
   */
  cache,

  /**
   * 状态管理
   */
  store: {} as Record<'app' | 'menus' | 'layout' | 'wk' | 'user' | string, any>
}

/**
 * 创建共享变量
 */
export const createShared = () => {
  const { route, router } = useRouterPlus()

  const userStore = useUserStore()
  const appStore = useAppSore()
  const layoutStore = useLayoutStore()
  const menusStore = useMenusStore()

  shared.route = route
  shared.router = router as unknown as TRouter
  shared.store.app = appStore
  shared.store.menus = menusStore
  shared.store.user = userStore
  shared.store.layout = layoutStore
}

let uid = 0

/**
 * 初始化共享属性
 * @param options
 */
export function initSharedProps(options?: Record<string, any>) {
  const layoutStore = useLayoutStore()
  createShared()

  return {
    id: ++uid,
    microId: layoutStore.tabsActive, // 当前tabKey
    platform: setting.platform, // 微前端主应用
    container: null,
    /**
     * 断言 路由是否可以跳转
     */
    assertRouteNextTo(options: { fullPath?: string }) {
      const key = options?.fullPath
      return key === layoutStore.tabsActive
    },
    entry: options?.entry,
    shared, // 分享数据【方便后期拓展】
    base: null // 基础路径
  }
}
